<?php

namespace lc\wechat\auth\Gateways;

use lc\helpers\Helper;
use think\facade\Config;
use think\facade\Cookie;
use think\facade\Db;

class Base
{
    protected $config = [];

    public function __construct()
    {
        $this->config = Config::get('lc.wechat');
    }

    /**
     * @desc    快速授权
     * @param   string      $scope
     * @param   string|null $redirect
     * @return  mixed
     */
    public function auth(string $scope = 'snsapi_userinfo', string $redirect = null)
    {
        $code = request()->get('code', null);
        if (!$code) {
            header('Location: ' . $this->authUrl($scope, $redirect));
            exit();
        }

        $openInfo = $this->code2Openid($code);
        if (isset($openInfo['errcode']) && in_array($openInfo['errcode'], [40163, 40029])) {
            header('Location: ' . $this->authUrl($scope, $redirect));
            exit();
        }
        if (isset($openInfo['errcode'])) {
            exit($openInfo['errmsg']);
        }
        if ($scope == 'snsapi_userinfo') {
            $userInfo = $this->userSimpleInfo($openInfo['access_token'], $openInfo['openid']);
            if ($userInfo && isset($userInfo['nickname'])) {
                $userInfo['nickname'] = Helper::filterEmoji($userInfo['nickname']);
            }
        } else {
            $userInfo['openid'] = $openInfo['openid'];
        }

        $baseTable = $this->config['appid'] . '_user';
        $userId = Db::table($baseTable)->where('openid', $userInfo['openid'])->value('user_id');
        if (empty($userId)) {
            $userId = Db::table($baseTable)
                ->insertGetId([
                    'openid'        => $userInfo['openid'],
                    'unionid'       => $userInfo['unionid'] ?? '',
                    'nickname'      => $userInfo['nickname'] ?? '',
                    'headimgurl'    => $userInfo['headimgurl'] ?? '',
                    'sex'           => $userInfo['sex'] ?? '',
                    'country'       => $userInfo['country'] ?? '',
                    'province'      => $userInfo['province'] ?? '',
                    'city'          => $userInfo['city'] ?? '',
                    'language'      => $userInfo['language'] ?? '',
                    'create_time'   => time()
                ]);
        }
        $userInfo['user_id'] = $userId;
        if ($this->config['cookie_write']) {
            $key = env('id') . '_user_' . Config::get('lc.auth.api.key');
            Cookie::set($key, Helper::encrypt($userId), $this->config['cookie_exp']);
        }
        return $userInfo;
    }

    /**
     * @desc    获取jssdk
     * @param   string $url 需要授权的地址
     * @param   array $api 开放接口列表
     * @param   array $tag 开发能力列表
     * @return  array
     */
    public function jssdk(string $url, $api = [], $tag = [])
    {
        $jsApiList = array_merge($api, [
            'checkJsApi',
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'hideMenuItems',
            'showMenuItems',
            'hideAllNonBaseMenuItem',
            'getLocalImgData',
            'chooseImage'
        ]);
        $openTagList = array_merge($tag, ['wx-open-launch-weapp', 'wx-open-launch-app']);
        $jsApiTicket = $this->jsApiTicket();
        $timestamp   = time();
        $nonceStr    = uniqid();

        return [
            'debug'         => false,
            'appId'         => $this->config['appid'],
            'timestamp'     => $timestamp,
            'nonceStr'      => $nonceStr,
            'signature'     => sha1('jsapi_ticket=' . $jsApiTicket . '&noncestr=' . $nonceStr . '&timestamp=' . $timestamp . '&url=' . $url),
            'jsApiList'     => $jsApiList,
            'openTagList'   => $openTagList
        ];
    }

    /**
     * @desc    获取授权地址
     * @param   string $scope 授权方式 snsapi_base|snsapi_userinfo
     * @param   string|null $redirect
     * @return  string
     */
    public function authUrl(string $scope = 'snsapi_userinfo', string $redirect = null): string {}

    /**
     * @desc    使用授权code换取openid
     * @param   string $code
     * @return  array
     */
    public function code2Openid(string $code): array {}

    /**
     * @desc    获取用户基础信息
     * @param   string $accessToken
     * @param   string $openid
     * @return  array
     */
    public function userSimpleInfo(string $accessToken, string $openid): array {}

    /**
     * @desc    获取用户详细信息
     * @param   string $openid
     * @return  array
     */
    public function userDetailInfo(string $openid): array {}

    /**
     * @desc    获取 JSAPI TICKET
     * @return  string
     */
    public function jsApiTicket() {}
}
